package com.fanrenqiji.common.utils;

import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

/**
 * Created by yanwt on 2017/3/13.
 */
@SuppressWarnings("unchecked")
public final class FreeMarkerUtils {

    /** FreeMarker默认配置 */
    private static final Configuration DEFAULT_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);

    /** BeansWrapper */
    private static final BeansWrapper DEFAULT_BEANS_WRAPPER = new BeansWrapperBuilder(Configuration.VERSION_2_3_22).build();


    /**
     * 不可实例化
     */
    private FreeMarkerUtils() {
    }

    /**
     * 解析字符串模板
     *
     * @param template
     *            字符串模板
     * @return 解析后内容
     */
    public static String process(String template) throws IOException, TemplateException {
        return process(template, null);
    }

    /**
     * 解析字符串模板
     *
     * @param template
     *            字符串模板
     * @param model
     *            数据
     * @return 解析后内容
     */
    public static String process(String template, Map<String, ?> model) throws IOException, TemplateException {
        return process(template, model, new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
    }

    /**
     * 解析字符串模板
     *
     * @param template
     *            字符串模板
     * @param model
     *            数据
     * @param configuration
     *            配置
     * @return 解析后内容
     */
    public static String process(String template, Map<String, ?> model, Configuration configuration) throws IOException, TemplateException {
        if (template == null) {
            return null;
        }
        StringWriter out = new StringWriter();
        new Template("template", new StringReader(template), configuration != null ? configuration : DEFAULT_CONFIGURATION).process(model, out);
        return out.toString();
    }

}